//
//  YDSQLManager.swift
//  YDWeibo01
//
//  Created by suibian on 16/8/22.
//  Copyright © 2016年 iitcast. All rights reserved.
//

import UIKit
//    数据库名称
private let myName = "YDSinaWeibo.db"
class YDSQLManager: NSObject {
//    全局访问点
    static let shareTools:YDSQLManager = YDSQLManager()
    //    以串行队列操纵数据库
    let queue:FMDatabaseQueue
//    重写init方法
    override init(){

//        路径
        let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent(myName)
        print(path)
        queue = FMDatabaseQueue(path: path)
        super.init()
        
//        创建数据库中的表
        creatTable()
    }
    func creatTable(){
//        准备sql
        let filePath = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
        let sql = try! String(contentsOfFile: filePath)
//        执行sql
        queue.inDatabase { (db) -> Void in
            if db.executeStatements(sql){
                print("创建表成功")
            
            }else{
                print("创建表失败")
            }
        }
        
    
    }

    // 传入一个sql语句帮其查询到结果
    func executeRecordForSql(sql: String) -> [[String: AnyObject]]{
        // 定义一个可变的数组
        var tempArray:[[String: AnyObject]] = [[String: AnyObject]]()
        // 执行sql
        YDSQLManager.shareTools.queue.inDatabase { (db) -> Void in
            let resultSet = db.executeQuery(sql, withArgumentsInArray: nil)
            // 遍历结果集(遍历每一行)
            while resultSet.next() {
                // 定义一个可变的字典
                var dict:[String: AnyObject] = [String: AnyObject]()
                // 循环列数(遍历每一列)
                for i in 0..<resultSet.columnCount() {
                    
                    let key = resultSet.columnNameForIndex(i)
                    let value = resultSet.objectForColumnIndex(i)
                    // 添加key value
                    dict[key] = value
                    
                }
                // 保存字典
                tempArray.append(dict)
            }
        }
        return tempArray
    }
 
}
